/**
 * @Author ouxueting
 */
package com.chinaunicom.tour.sys.controller;
import com.chinaunicom.tour.sys.constant.ResultConstants;

import com.chinaunicom.tour.sys.entity.User;

import com.chinaunicom.tour.sys.model.UserModel;
import com.chinaunicom.tour.sys.service.UserService;
import com.chinaunicom.tour.sys.util.CreatePwdUtil;
import com.chinaunicom.tour.sys.util.MailUtil;
import com.chinaunicom.tour.sys.util.ObjectRestResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Api(value = "用户账户信息", tags = { "用户账户信息" })
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    UserService userService;


    @ApiOperation(value = "用户登陆", notes = "")
    @RequestMapping(value = "login", method = RequestMethod.POST)
    @ResponseBody
    public ObjectRestResponse<User> login(@RequestBody UserModel entity, HttpServletRequest request) {
        ObjectRestResponse<User> orr = new ObjectRestResponse<User>();
        HttpSession session = request.getSession();

        try {
            //空校验
            if(isEmpty(entity.getUserName())||isEmpty(entity.getPwd())){
                orr.setStatus(ResultConstants.ERROR_CODE);
                orr.setMessage("请输入用户名和密码" );
                return orr;
            }
            //验证码检验
            ObjectRestResponse<String> orr2= checkVerification(entity.getVerificationCode(),session);
            if (orr2.getStatus()==ResultConstants.ERROR_CODE) {
                orr.setStatus(ResultConstants.ERROR_CODE);
                orr.setMessage(orr2.getMessage());
                return orr;
            } else {
                // 验证用户名密码
                User user = userService.findByUserNameAndPwd(entity);
                if (user==null){
                    orr.setStatus(ResultConstants.ERROR_CODE);
                    orr.setMessage("用户名/密码不正确" );
                    return orr;
                }else{
                    user.setPwd(null);
                    session.setAttribute("user",user);
                    orr.setData(user);
                    orr.setStatus(ResultConstants.SUCCESS_CODE);
                    orr.setMessage("登陆成功");
                }
                return orr;
            }
        } catch (Exception e) {
            e.printStackTrace();
            orr.setStatus(ResultConstants.ERROR_CODE);
            orr.setMessage("查询失败" + e.getMessage());
            return orr;
        }
    }




    @ApiOperation(value = "用户注册", notes = "")
    @RequestMapping(value = "regist", method = RequestMethod.POST)
    @ResponseBody
    public ObjectRestResponse<User> regist(@RequestBody UserModel entity,HttpServletRequest request) {
        ObjectRestResponse<User> orr = new ObjectRestResponse<User>();
        HttpSession session = request.getSession();
        try {
            //不为空校验为空
            if (isEmpty(entity.getUserName())||isEmpty(entity.getPwd())||isEmpty(entity.getEmail())||isEmpty(entity.getNickName())) {
                orr.setStatus(ResultConstants.ERROR_CODE);
                orr.setMessage("请输入用户名，密码，邮箱，昵称");
                return orr;
            }
            //用户名规则校验
            if (!checkUserName(entity.getUserName())) {
                orr.setStatus(ResultConstants.ERROR_CODE);
                orr.setMessage("用户名不符合规则");
                return orr;
            }

            //昵称校验规则
            if(!checkNickName(entity.getNickName())){
                orr.setStatus(ResultConstants.ERROR_CODE);
                orr.setMessage("昵称不符合规则");
                return orr;
            }

            //密码校验规则
            if(!checkPassword(entity.getPwd())){
                orr.setStatus(ResultConstants.ERROR_CODE);
                orr.setMessage("密码不符合规则");
                return orr;
            }
            //邮箱校验
            if(!checkEmail(entity.getEmail())){
                orr.setStatus(ResultConstants.ERROR_CODE);
                orr.setMessage("邮箱格式不正确");
                return orr;
            }

            //验证码检验
            ObjectRestResponse<String> orr2= checkVerification(entity.getVerificationCode(),session);
            if (orr2.getStatus()==ResultConstants.ERROR_CODE) {
                orr.setStatus(ResultConstants.ERROR_CODE);
                orr.setMessage(orr2.getMessage());
                return orr;
            }

            ObjectRestResponse<User> objectRestResponse = findByUserName(entity.getUserName());
            if (objectRestResponse.getStatus() == ResultConstants.SUCCESS_CODE) {
                if (objectRestResponse.getData() == null) {

                    User user = new User();
                    user.setUserName(entity.getUserName());
                    user.setPwd(entity.getPwd());
                    user.setEmail(entity.getEmail());
                    user.setNickName(entity.getNickName());

                    int num = userService.add(user);
                    if (num > 0) {
                        user.setPwd(null);
                        orr.setData(user);
                        orr.setStatus(ResultConstants.SUCCESS_CODE);
                        orr.setMessage("添加成功");
                        return orr;
                    } else {
                        orr.setStatus(ResultConstants.ERROR_CODE);
                        orr.setMessage("添加失败");
                        return orr;
                    }

                } else {
                    orr.setStatus(ResultConstants.ERROR_CODE);
                    orr.setMessage("用户名已存在");
                    return orr;
                }
            } else {
                orr.setStatus(ResultConstants.ERROR_CODE);
                orr.setMessage(objectRestResponse.getMessage());
                return orr;
            }


        } catch (Exception e) {
            e.printStackTrace();
            orr.setStatus(ResultConstants.ERROR_CODE);
            orr.setMessage("添加失败" + e.getMessage());
            return orr;
        }
    }

    /**
     * 更改密码和用户昵称
     * @return
     */
    @ApiOperation(value = "更改用户名密码", notes = "")
    @RequestMapping(value = "updatePwdAndNickName", method = RequestMethod.PUT)
    @ResponseBody
    public ObjectRestResponse<User> updatePwdAndNickName(@RequestBody User entity, HttpServletRequest request){

        ObjectRestResponse<User> orr = new ObjectRestResponse<User>();
        HttpSession session = request.getSession();
        //登陆状态判断
        User user = (User)session.getAttribute("user");
        if(user==null){
            orr.setStatus(ResultConstants.ERROR_CODE);
            orr.setMessage("请先登陆");
            return orr;
        }
        try {

            //密码校验
            if(!isEmpty(entity.getPwd())){
               if(!checkPassword(entity.getPwd())) {
                   orr.setStatus(ResultConstants.ERROR_CODE);
                   orr.setMessage("密码不符合规则" );
                   return orr;
               }
            }
            //昵称校验
            if(!isEmpty(entity.getNickName())){
                if (!checkNickName(entity.getNickName())){
                    orr.setStatus(ResultConstants.ERROR_CODE);
                    orr.setMessage("昵称不符合规则" );
                    return orr;
                }
            }
            int num = userService.update(entity);
            if(num>0){
                user.setNickName(entity.getNickName());
                session.setAttribute("user",user);
                orr.setStatus(ResultConstants.SUCCESS_CODE);
                orr.setMessage("更新成功");
                orr.setData(user);
                return orr;

            }else{
                orr.setStatus(ResultConstants.ERROR_CODE);
                orr.setMessage("修改失败");
                return orr;
            }

        }catch (Exception e){
            orr.setStatus(ResultConstants.ERROR_CODE);
            orr.setMessage("修改失败" + e.getMessage());
            return orr;
        }

    }

    /**
     * 忘记密码，密码自动重置
     * @param entity
     * @return
     */
    @ApiOperation(value = "忘记密码", notes = "")
    @RequestMapping(value = "resetPwd", method = RequestMethod.PUT)
    @ResponseBody
    public ObjectRestResponse<User> resetPwd(@RequestBody UserModel entity,HttpServletRequest request){
        ObjectRestResponse<User> orr = new ObjectRestResponse<User>();

        //空校验
        if (isEmpty(entity.getUserName())||isEmpty(entity.getEmail())){
            orr.setStatus(ResultConstants.ERROR_CODE);
            orr.setMessage("请输入用户名/邮箱");
            return orr;
        }
        try {
            ObjectRestResponse<User> orr2 = findByUserNameAndEmil(entity);
            if(orr2.getStatus()==ResultConstants.SUCCESS_CODE){

                User user = orr2.getData();
                if(user==null){
                    orr.setStatus(ResultConstants.ERROR_CODE);
                    orr.setMessage("用户名/邮箱输入错误");
                    return orr;
                }else{
                    //生成随机密码
                    String newPwd = CreatePwdUtil.getPwd();
                    String pwdMd5 = CreatePwdUtil.md5(newPwd);
                    user.setPwd(pwdMd5);
                    int num =userService.update(user);
                    if(num >0){
                        //发送邮件
                        user.setPwd(newPwd);
                        MailUtil.sendEmail(user);
                        user.setPwd(null);
                        orr.setData(user);
                        orr.setStatus(ResultConstants.SUCCESS_CODE);
                        orr.setMessage("修改成功");
                        return orr;
                    }else {
                        orr.setStatus(ResultConstants.ERROR_CODE);
                        orr.setMessage("修改失败");
                        return orr;
                    }
                }
            }else{
                orr.setStatus(ResultConstants.ERROR_CODE);
                orr.setMessage(orr2.getMessage());
                return orr;
            }
        }catch (Exception e){
            orr.setStatus(ResultConstants.ERROR_CODE);
            orr.setMessage("修改失败"+e.getMessage());
            return orr;
        }
    }


    @ApiOperation(value = "根据id查询", notes = "")
    @RequestMapping(value = "findById/{id}", method = RequestMethod.GET)
    @ResponseBody
    public ObjectRestResponse<User> findById(@PathVariable String id) {
        ObjectRestResponse<User> orr = new ObjectRestResponse<User>();
        try {
            User user = userService.findById(id);
            user.setPwd(null);
            orr.setData(user);
            orr.setStatus(ResultConstants.SUCCESS_CODE);
            orr.setMessage("查询成功");
            return orr;
        } catch (Exception e) {
            e.printStackTrace();
            orr.setStatus(ResultConstants.ERROR_CODE);
            orr.setMessage("查询失败" + e.getMessage());
            return orr;
        }
    }

    /**
     * 查询用户名邮箱
     * @param entity
     * @return
     */
    public ObjectRestResponse<User> findByUserNameAndEmil(UserModel entity) {
        ObjectRestResponse<User> orr = new ObjectRestResponse<User>();

        try {
            User user = userService.findByUserNameAndEmail(entity);
            orr.setData(user);
            orr.setStatus(ResultConstants.SUCCESS_CODE);
            orr.setMessage("查询成功");
            return orr;
        } catch (Exception e) {
            e.printStackTrace();
            orr.setStatus(ResultConstants.ERROR_CODE);
            orr.setMessage("查询失败" + e.getMessage());
            return orr;
        }
    }

    /**
     * 查询用户名是否存在
     * @param userName
     * @return
     */
    public ObjectRestResponse<User> findByUserName(String userName) {
        ObjectRestResponse<User> orr = new ObjectRestResponse<User>();

        try {
            User user = userService.findByUserName(userName);
            orr.setData(user);
            orr.setStatus(ResultConstants.SUCCESS_CODE);
            orr.setMessage("查询成功");
            return orr;
        } catch (Exception e) {
            e.printStackTrace();
            orr.setStatus(ResultConstants.ERROR_CODE);
            orr.setMessage("查询失败" + e.getMessage());
            return orr;
        }
    }

    /**
     * 用户名规则：最少6位，必须以英文字母开头，可使用英文字母，数字或下划线；
     * @return
     */
    public boolean checkUserName(String userName){

            // 指定判断规则(中括号内字符顺序随便)
            Pattern p = Pattern.compile("^[a-zA-Z]{1}[a-zA-Z\\d\\_]{5,}");
            // 进行规则匹配
            Matcher m = p.matcher(userName);
            // 进行判断
            boolean flag = m.matches();
            return flag;
    }

    /**
     * 用户密码规则：最少8位；
     * @return
     */
    public boolean checkPassword(String pwd){

        if(pwd.length()>=8){
            return true;
        }
        return false;
    }
    /**
     * 昵称长度校验
     * @param nickName
     * @return
     */
    public boolean checkNickName(String nickName){
        if(nickName.length()>=4){
            return true;
        }
        return false;
    }

    /**
     * 字段空校验
     * @param str
     * @return
     */
    public boolean isEmpty(String str){

        if("".equals(str)|| str==null){
            return true;
        }
        return false;
    }

    public boolean checkEmail(String mail){

        // 指定判断规则(中括号内字符顺序随便)
        Pattern p = Pattern.compile("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$");
        // 进行规则匹配
        Matcher m = p.matcher(mail);
        // 进行判断
        boolean flag = m.matches();
        return flag;
    }

    /**
     * 判断验证码是否正确
     * @param verificationCode
     * @param session
     * @return
     */
    public ObjectRestResponse<String> checkVerification(String verificationCode,HttpSession session) {

        ObjectRestResponse<String> orr = new ObjectRestResponse<String>();

        // 获得验证码对象
        Object codeObj = session.getAttribute("verificationCode");
        Object codeTimeObj = session.getAttribute("codeTime");
        if (codeObj == null || codeTimeObj == null) {
            orr.setStatus(ResultConstants.ERROR_CODE);
            orr.setMessage("验证码已失效，请重新输入！");
            return orr;
        }
        String code = codeObj.toString();
        // 验证码有效时长为1分钟
        Date now = new Date();
        Long codeTime = Long.valueOf(codeTimeObj + "");
        if ((now.getTime() - codeTime) / 1000 / 60 > 1) {
            orr.setStatus(ResultConstants.ERROR_CODE);
            orr.setMessage("验证码已失效，请重新输入！");
            return orr;
            // 判断验证码输入是否正确
        } else if ("".equals(verificationCode) || verificationCode == null || !(verificationCode.equalsIgnoreCase(code))) {
            orr.setStatus(ResultConstants.ERROR_CODE);
            orr.setMessage("验证码错误，请重新输入！");
            return orr;
        } else {
            orr.setStatus(ResultConstants.SUCCESS_CODE);
            orr.setMessage("验证码正确");
            return orr;
        }
    }
}
